package chatBot.controller;

import chatBot.common.Result;
import chatBot.entity.User;
import chatBot.repository.UserRepository;
import chatBot.service.impl.WeChatServiceImpl;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static chatBot.constans.RedisConstant.USER_TOKEN_KEY;

/**
 * @author a2426
 */
@Slf4j
@RestController
@RequestMapping("/gpt")
@Validated
public class WeChatController {

    @Resource
    StringRedisTemplate  stringRedisTemplate ;

    @Autowired
    private WeChatServiceImpl weChatService;

    @Autowired
    private UserRepository userRepository;

    @GetMapping("/checkUserState")
    public Result<Map> checkUserState() {
        Map<String, Object> res = new HashMap<String, Object>();
        User user = userRepository.findByState(1).orElse(new User());
        if (new Integer(1).equals(user.getState())) {
            String token = (String) stringRedisTemplate.opsForValue().get(USER_TOKEN_KEY + user.getUserId());
            if (token != null) {
                res.put("user",user);
                res.put("token",token);
                return Result.success(res);
            }
        }
        log.info("此次监听没有用户在线！");
        return Result.success(res);

    }

    /**
     * 微信登录
     *
     * @param userInfo
     * @return
     * @throws IOException
     */
    @PostMapping("/wxlogin")
    public Map<String, Object> login(@Valid @RequestBody Map<String, String> userInfo) throws IOException {
        String code = userInfo.get("code");
        System.out.println(code);
        String username = userInfo.get("username") + IdWorker.getId();

        User user = weChatService.login(code, username);

        Map<String, Object> response = new HashMap<>();
        response.put("need", Objects.equals(user.getUserEmail(), "defaultEmail@qq.com"));
        response.put("user", user);
        return response;
    }

    /**
     * 用户首次登录绑定邮箱
     *
     * @param bindingInfo
     * @return
     */
    @PostMapping("/bind")
    public Result<Map> bind(@Valid @RequestBody Map<String, String> bindingInfo) {
        String openId = bindingInfo.get("openId");
        String email = bindingInfo.get("email");
        String password = bindingInfo.get("password");
        Map<String, Object> map = weChatService.bind(openId, email, password);

        return Result.success(map);
    }
}
